package com.dataseek.iot.device.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dataseek.iot.device.entity.DeviceAttrValue;
import com.dataseek.iot.device.entity.MqttLog;
import com.dataseek.iot.device.mapper.DeviceAttValueMapper;
import com.dataseek.iot.device.service.MqttLogService;
import com.dataseek.iot.mqtt.entity.SendMessage;
import com.dataseek.iot.mqtt.service.ISendMessage;
import com.dataseek.iot.toolikit.common.enums.RspStatusEnum;
import com.dataseek.iot.toolikit.common.response.ResponseResult;
import com.dataseek.iot.toolikit.common.service.IDServiceHelper;
import com.dataseek.iot.toolikit.common.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
@Slf4j
public class SendController {

    @Autowired
    private ISendMessage iMqttSender;

    @Autowired
    private MqttLogService mqttLogService;

    @Autowired
    private IDServiceHelper idServiceHelper;

    @Autowired
    private DeviceAttValueMapper deviceAttValueMapper;
    /**
     *  发送自定义消息内容（使用默认主题）
     * @param data
     */
    @GetMapping(value = "/send")
    public void test1(SendMessage data) {
        JSONObject json = (JSONObject) JSONObject.toJSON(data);
        log.info("----->{}","mqtt 消息发布，使用默认主题发布:"+json.toJSONString());
        iMqttSender.sendToMqtt(data.getMessagebody());
    }

    /**
     *  发送自定义消息内容，且指定主题
     * @param topic,messegeBody
     */
    @RequestMapping("/send/topic")
    public ResponseResult test2(@RequestParam(value="topic")String topic,@RequestBody Map paramMp) {
        String message = JSONObject.toJSONString(paramMp, SerializerFeature.WriteMapNullValue);
        iMqttSender.sendToMqtt(topic, message);
        return new ResponseResult(RspStatusEnum.SUCCESS.getCode(),"成功!", "0");
    }

    /**
     * 设备新建时候，需要通过发送MQTT，通过deviceid获取设备属性
     * @param ProductId
     * @param DeviceId
     * @return
     */
    @RequestMapping("/send/readDeviceInfo")
    public ResponseResult readDeviceInfo(@RequestParam(value="pdtCode", required=false) String pdtCode,
                                         @RequestParam(value="deviceCode", required=true) String deviceCode ) {
        //Properties存放属性字段，格式：sn,model
        Map paramMp=new HashMap();

        Long currentTime=System.currentTimeMillis();
        UUID uuid = UUID.randomUUID();
        String messageId = uuid.toString();

        //属性需要加上“”，通过设备获取属性
        QueryWrapper qw =new QueryWrapper();
        qw.eq("device_code",deviceCode);
        List<DeviceAttrValue> deviceAttrValueList= deviceAttValueMapper.selectList(qw);
        int len=deviceAttrValueList.size();
        String[] Properties=new String[len];
        for(int i=0;i<len;i++){
            pdtCode=deviceAttrValueList.get(0).getPdtCode();
            Properties[i]=deviceAttrValueList.get(i).getAttCode();
        }
        paramMp.put("timestamp",currentTime);
        paramMp.put("messageId",messageId);
        paramMp.put("deviceId",deviceCode);
        paramMp.put("properties",Properties);
        //topic
        String topic="/"+pdtCode+"/"+deviceCode+"/properties/read";
        String message = JSONObject.toJSONString(paramMp, SerializerFeature.WriteMapNullValue);
        System.out.println("========read========"+message);
        //发送/{productId}/{deviceId}/properties/read 读取设备属性
        iMqttSender.sendToMqtt(topic, message);

        MqttLog mqttLog=new MqttLog();
        //保存发送日志
        long id = idServiceHelper.nextId();
        mqttLog.setMqttLogId(id);
        mqttLog.setTopic(topic);
        mqttLog.setMessage(message);
        mqttLog.setMessageId(messageId);
        mqttLog.setTimestamp(currentTime);
        mqttLog.setSendTime(DateUtils.getDateTimeNowStr());
        mqttLogService.insertAction(mqttLog);

        return new ResponseResult(RspStatusEnum.SUCCESS.getCode(),"成功!", "0");
    }

    /**
     *
     * @param ProductId
     * @param DeviceId
     * @return
     */
    @RequestMapping("/send/writeDeviceInfo")
    public ResponseResult writeDeviceInfo(@RequestParam(value="pdtCode", required=false) String pdtCode,
                                          @RequestParam(value="deviceCode", required=true) String deviceCode) {
        //Properties存放属性字段
        Map paramMp=new HashMap();

        Long currentTime=System.currentTimeMillis();
        UUID uuid = UUID.randomUUID();
        String messageId = uuid.toString();

        paramMp.put("timestamp",currentTime);
        paramMp.put("messageId",messageId);
        paramMp.put("deviceId",deviceCode);
        //根据设备code查询设备属性
        Map Properties=new HashMap();
        QueryWrapper qw =new QueryWrapper();
        qw.eq("device_code",deviceCode);
        List<DeviceAttrValue> deviceAttrValueList= deviceAttValueMapper.selectList(qw);

        for(DeviceAttrValue deviceAttrValue:deviceAttrValueList){
            pdtCode=deviceAttrValue.getPdtCode();
            //可读状态下发write
            if(deviceAttrValue.getReadFlag().equals("0")) {
                Properties.put(deviceAttrValue.getAttCode(), deviceAttrValue.getAttValue());
            }
        }
        paramMp.put("properties",Properties);

        String message = JSONObject.toJSONString(paramMp, SerializerFeature.WriteMapNullValue);
        String topic="/"+pdtCode+"/"+deviceCode+"/properties/write";
        System.out.println("======write=========="+message);
        //调用topic，发送mqtt的write接口，还需要加上订阅接口reply
        iMqttSender.sendToMqtt(topic, message);

        MqttLog mqttLog=new MqttLog();
        //保存发送日志
        long id = idServiceHelper.nextId();
        mqttLog.setMqttLogId(id);
        mqttLog.setTopic(topic);
        mqttLog.setMessage(message);
        mqttLog.setMessageId(messageId);
        mqttLog.setTimestamp(currentTime);
        mqttLog.setSendTime(DateUtils.getDateTimeNowStr());
        mqttLogService.insertAction(mqttLog);

        return new ResponseResult(RspStatusEnum.SUCCESS.getCode(),"成功!", "0");
    }
}